package com.gitee.wsl.struct.generator.sample

import com.gitee.wsl.ext.base.currentTimeMillis
import com.gitee.wsl.time.toLocalDateTime
import kotlin.random.Random
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue


/**
 * @author Mingo.Liu
 * @date 2023-11-28
 */
class OrderIdGeneratorTest {
    private val idGenerator: OrderIdGenerator = OrderIdGenerator(5)

    private val type = 4

    @Test
    fun generate() {
        val id: Long = idGenerator.generate("A00001", type)
        assertEquals(16, id.toString().length)
    }

    @Test
    fun validate() {
        val shopId = "A00001"
        var id: Long = idGenerator.generate(shopId, type)
        assertTrue(idGenerator.validate(shopId, id))
        assertFalse(idGenerator.validate(shopId, ++id))
        assertFalse(idGenerator.validate("A000111", id))
    }

    @Test
    fun parse() {
        val shopId = "1234567"
        val id: Long = idGenerator.generate(shopId, type)
        val results: Array<Long> = idGenerator.parse(shopId, id)

        val timestamp = results[0]
        val dateTime = timestamp.toLocalDateTime()
        println("Time: $dateTime" )
        println("Machine id: " + results[1])
        println("Type: " + results[2])
        println("Sequence: " + results[3])
    }

    @Test
    fun performance() {
        val shopId = "TTT600001"
        val num: Long = 1000
        val startTime: Long = currentTimeMillis
        for (i in 0 until num) {
            val id: Long = idGenerator.generate(shopId, type)
            println(id)
        }
        println("Spends " + (currentTimeMillis - startTime))
    }

    @Test
    fun crash() {
        val shopId = "A00001"
        val num: Long = 10000000
        var passNum: Long = 0

        for (i in 0 until num) {
            val sb: StringBuilder = StringBuilder()
            for (j in 0..15) {
                sb.append(Random.nextInt(100) / 10)
            }

            val id: Long = sb.toString().toLong()
            if (idGenerator.validate(shopId, id)) {
                passNum++
            }
        }

        println(passNum)
    }

    @Test
    fun crash1() {
        val shopId = "A00001"
        val num: Long = 100000000
        var passNum: Long = 0
        var id: Long = idGenerator.generate(shopId, type)
        for (i in 0 until num) {
            if (idGenerator.validate(shopId, ++id)) {
                passNum++
            }
        }

        println(passNum)
    }
}
